import { Context } from 'koa'
import { getListSer, addSer, putSer, getDetailSer, delSer } from '@/business/service'
import { userType} from '@/types'
import {  IshebeileixingQueryType, IshebeileixingQuerySerType, Ishebeileixing, IshebeileixingSer } from '@/types/equipment/shebeileixing'
import errors from '@/app/err.type'
import { formatHumpLineTransfer } from '@/business/utils'
import { excelJsExport } from '@/business/utils/excel'
import {  excelBaseStyle } from '@/business/public/excelMap'
import ShebeileixingTable from '@/mysql/model/equipment/shebeileixing.model'
import { Op } from 'sequelize'
const { uploadParamsErr, getListErr, sqlErr, delErr, exportExcelErr} = errors

// 获取列表
export const getListMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const { pageNum, pageSize, ...params } = ctx.query as unknown as IshebeileixingQueryType
    let newParams = { pageNum, pageSize } as IshebeileixingQuerySerType
    if(params.fileType) newParams.file_type = { [Op.eq]: params.fileType  }
    if(params.name) newParams.name = { [Op.eq]: params.name  }
    
    const res = await getListSer<IshebeileixingQuerySerType>(ShebeileixingTable, newParams)

    ctx.state.formatData = res
    await next()
  } catch (error) {
    console.error('查询列表失败', error)
    return ctx.app.emit('error', getListErr, ctx)
  }
}

// 新增
export const getAddMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const { userName } = ctx.state.user as userType
    const addContent = ctx.request['body'] as Ishebeileixing
    const addContent2 = { ...addContent, createBy: userName }
    const newAddContent = formatHumpLineTransfer(addContent2, 'line') as  IshebeileixingSer
    if (await isDuplicate(newAddContent)) {
      return ctx.app.emit('error', {code:'500',message:'新增失败,设备类型重复'}, ctx)
    }
    await addSer<IshebeileixingSer>(ShebeileixingTable, newAddContent)
    await next()
  } catch (error) {
    console.error('新增失败', error)
    return ctx.app.emit('error', uploadParamsErr, ctx)
  }
}

// 删除
export const delMid = async (ctx: Context, next: () => Promise<void>) => {
  try {

    await delSer(ShebeileixingTable, { table_id: ctx.state.ids })
  } catch (error) {
    console.error('删除失败', error)
    return ctx.app.emit('error', delErr, ctx)
  }

  await next()
}

// 获取详细数据
export const getDetailMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const res = await getDetailSer<IshebeileixingSer>(ShebeileixingTable, { table_id: ctx.state.ids  })

    ctx.state.formatData = res
  } catch (error) {
    console.error('详细数据查询错误', error)
    return ctx.app.emit('error', sqlErr, ctx)
  }

  await next()
}

// 修改
export const putMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const { userName } = ctx.state.user as userType
    const res = ctx.request['body'] as Ishebeileixing
    const lineData =  formatHumpLineTransfer(res, 'line') as IshebeileixingSer
    const { table_id} = lineData

    await putSer<IshebeileixingSer>(ShebeileixingTable, { table_id}, { ...lineData, update_by: userName })

    await next()
  } catch (error) {
    console.error('修改失败', error)
    return ctx.app.emit('error', uploadParamsErr, ctx)
  }
}

// 导出
export const exportMid = async (ctx: Context, next: () => Promise<void>) => {
  try {
    const list = ctx.state.formatData
    const dicts = ctx.state.dicts

    // 表格数据
    const buffer = await excelJsExport({
      sheetName: '设备类型',
      style: excelBaseStyle,
      headerColumns: [{"title":"设备类型","dataIndex":"file_type"},{"title":"设备名称","dataIndex":"name"}],
      tableData: list,
      dicts: dicts
    })
    ctx.state.buffer = buffer
    await next()
  } catch (error) {
    console.error('导出失败', error)
    return ctx.app.emit('error', exportExcelErr, ctx)
  }
}

// 设备类型判重
export const isDuplicate = async (lineData) => {
  try {
    const {file_type} = lineData
    const whereOpt = {file_type};
    // 查找是否重复
    const res = (await ShebeileixingTable.findOne({
      attributes: ['file_type', 'name'],
      where: whereOpt,
    })) as any;
    return res ? res.dataValues : null;    
  } catch (error) {
    console.log(error)
  }
}